<template>
  <div>
    <h1>购物车</h1>
    <ul>
      <li v-for="item in cartItems" :key="item.id">
        {{ item.name }} - ¥{{ item.price }} - 数量：{{ item.quantity }}
        <button @click="increment(item.id)">+</button>
        <button @click="decrement(item.id)">-</button>
        <button @click="removeFromCart(item.id)">删除</button>
      </li>
    </ul>
    <p>总价： ¥{{ cartTotalPrice }}</p>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['cartItems']),
    ...mapGetters(['cartTotalPrice'])
  },
  methods: {
    ...mapActions(['addToCart', 'removeFromCart', 'updateCartItemQuantity']),
    increment(itemId) {
      const item = this.cartItems.find(i => i.id === itemId);
      if (item) {
        this.updateCartItemQuantity({ itemId, quantity: item.quantity + 1 });
      }
    },
    decrement(itemId) {
      const item = this.cartItems.find(i => i.id === itemId);
      if (item) {
        if (item.quantity > 0) {
          this.updateCartItemQuantity({ itemId, quantity: item.quantity - 1 });
        }
      }
    },
    removeFromCart(itemId) {
      this.$store.commit('removeFromCart', itemId);
    }
  }
};
</script>

<style scoped>
button {
  margin: 0 5px;
  padding: 5px 10px;
  cursor: pointer;
  display: inline-block;
  border: 1px solid #ccc;
}

button:hover {
  background-color: #f0f0f0;
}
</style>